package com.qf.channel;

import com.alibaba.fastjson.JSON;
import com.qf.entity.Msg;
import com.qf.util.ChannelUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(0)
@ChannelHandler.Sharable
public class MsgInitChannelHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("有一个新的客户端连接了服务器！");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("有一个客户端断开了连接！");
        ChannelUtil.delChannel(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String content = textWebSocketFrame.text();
        //字符串转换成 Msg对象
        try {
            Msg msg = JSON.parseObject(content, Msg.class);
            //将消息继续往后传递
            ctx.fireChannelRead(msg);
        } catch (Exception e) {
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //说明客户端通讯出现问题
        ChannelUtil.delChannel(ctx.channel());
    }
}
